package org.knot.autojmx.spring;

import java.util.concurrent.ConcurrentHashMap;

import org.knot.autojmx.AnnotationAutoJMXHandler;
import org.knot.autojmx.AutoJMXHandler;
import org.knot.autojmx.annotations.AutoJMX;
import org.knot.autojmx.api.AutoJMXAPI;
import org.knot.autojmx.exception.AutoJMXException;
import org.knot.autojmx.utils.SpringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.stereotype.Component;


/**
 * 
 * AutoJMX与spring的交互接口
 * 
 *@author  <a href="mailto:yuxiaoweimail@gmail.com">yuxiaowei</a>
 */
@Component("autojmx")
public class AutoJMXPostProcessor implements DestructionAwareBeanPostProcessor {

//	private static ConcurrentHashMap<String, AutoJMXHandler> handlers = new ConcurrentHashMap<String, AutoJMXHandler>();
//
//	public static ConcurrentHashMap<String, AutoJMXHandler> getHandlers() {
//		return handlers;
//	}
//
//	public static AutoJMXHandler getHandler(String name) {
//		return handlers.get(name);
//	}
	
	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor#postProcessBeforeDestruction(java.lang.Object, java.lang.String)
	 */
	@Override
	public void postProcessBeforeDestruction(Object bean, String beanName)
			throws BeansException {
		Object targetBean = bean;
		try {
			targetBean = SpringUtils.getUserTarget(bean);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		AutoJMX jmxBean = targetBean.getClass().getAnnotation(AutoJMX.class);
		if (null != jmxBean) {
			AutoJMXAPI.Instance().destoryJMXBean(bean, beanName);
		}
	}
 
	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
	 */
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName)
			throws BeansException {
		Object targetBean = bean;
		try {
			targetBean = SpringUtils.getUserTarget(bean);
		} catch (Exception e) {
			// e.printStackTrace();
		}
		AutoJMX jmxBean = targetBean.getClass().getAnnotation(AutoJMX.class);
		if (null != jmxBean) {
			try {
				AutoJMXAPI.Instance().createJMXBean(bean, beanName);
			} catch (AutoJMXException e) {
				//e.getMessage()
			}
		}
		return bean;
	}
 
	/* (non-Javadoc)
	 * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization(java.lang.Object, java.lang.String)
	 */
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName)
			throws BeansException {
		return bean;
	}
}
